$(function() {
	$('a.propose_show').click(function(e) {
		$('div.search_results').show();
		$('div.search_results.s_opened').hide();
		var p = $(this).parents('div.search_results');
		var d = $(this).metadata();
		var ajaxData = {item_index: d.index, user_id: d.userId, rate_id: d.rateId, markup: d.markup, vendor: d.vendorId};

		/* Simple correction (if vendorId is undefined - remove it from data array) */
		if (d.vendorId == '') {
			delete ajaxData['vendor'];
		}
		
/*		if ($('.hotel_search_results').length > 0) {
			timer = window.setTimeout(function() {searchWaitRedirect(d.index);}, tm.Config.searchResultsTimeout);
		}*/
		
		if (p.next(0).hasClass('s_opened')) {
			$('#popupOverlay').hide();
			$('#popupLoading').hide();
			$('#popupWindow').hide();
			p.find('a.propose_show').removeClass('popup');
			p.find('a.propose_show').removeClass('wait-screen');
			p.next(0).find('.propositions .service_choose .row .input a.tm-radiobutton').each(function() {
				if (!$(this).prev(0).is(':radio')) {
					$(this).remove();
				}
			});
			p.hide();
			p.next(0).show();
			if ($('.hotel_search_results').length > 0) {
				searchResultsEvents();
			}
		} else {
			if ($('.hotel_search_results').length > 0) {
				$.get('/a_ajax/avail/hotel.search', ajaxData, function(data) {
					//window.clearTimeout(timer);
					tm.Popup.popupClose();
					if (data == 'error') {
						if(!location.href.match(/expandHotel=/i)) {
							location.href += '&expandHotel=' + d.index;
						}
						return;
					}
					p.hide().after(data);
					p.find('a.propose_show').removeClass('popup');
					p.find('a.propose_show').removeClass('wait-screen');
					$('.service_choose :radio').each(function () {
						tm.FormControls.addRadioButtonGroup(this);
						tm.FormControls.replaceRadioButton(this);
					});
					if (!p.next(0).find('.search_results_item .photo a img').hasClass('default')) {
						var thisIMG = p.next(0).find('.search_results_item .photo a img');
						var thisSRC = thisIMG.attr('src');
						var thisWIDTH = thisIMG.attr('width');
						var thisHEIGHT = thisIMG.attr('height');
						var thisALT = thisIMG.attr('alt');
						p.find('.search_results_item .photo a img').removeClass('default').attr({
							src: thisSRC,
							width: thisWIDTH,
							height: thisHEIGHT,
							alt: thisALT
						});
					}
					$('a.propose_hide').click(function() {
						var s = $(this).parents('div.search_results.s_opened');
						s.prev().show();
						s.hide();
					});
					$(this).parents('.search_results').next(0).find('.system-hotels-search .mapping input').attr('id', 'mapping-opened-' + d.index);
					$(this).parents('.search_results').next(0).find('.system-hotels-search .mapping label').attr('for', 'mapping-opened-' + d.index);
					searchResultsEvents();
				});
			} else if ($('.car_search_results').length > 0) {
				function fieldsetsBind() {
					var fieldset = $(this).parents('fieldset');
					if (fieldset.hasClass('expanded')) {
						fieldset.find('div.body').slideUp(function() {
							fieldset.removeClass('expanded').addClass('collapsed');
						});
					} else if (fieldset.hasClass('collapsed')) {
						fieldset.find('div.body').slideDown();
						fieldset.removeClass('collapsed').addClass('expanded');
					}
				}
				ajaxData = {item_index: d.index, user_id: d.userId, rate_id: d.rateId};
				$.get('/a_ajax/avail/car.search', ajaxData, function(data) {
					tm.Popup.popupClose();
					/*if (data == 'error') {
						if(!location.href.match(/expandHotel=/i)) {
							location.href += '&expandHotel=' + d.index;
						}
						return;
					}*/
					p.hide().after(data);
					p.find('a.propose_show').removeClass('popup');
					p.find('a.propose_show').removeClass('wait-screen');
					tm.FormControls.init();
					p.next(0).find('.car-more-info fieldset legend a').bind('click', fieldsetsBind);
					/*
					if (!p.next(0).find('.search_results_item .photo a img').hasClass('default')) {
						var thisIMG = p.next(0).find('.search_results_item .photo a img');
						var thisSRC = thisIMG.attr('src');
						var thisWIDTH = thisIMG.attr('width');
						var thisHEIGHT = thisIMG.attr('height');
						var thisALT = thisIMG.attr('alt');
						p.find('.search_results_item .photo a img').removeClass('default').attr({
							src: thisSRC,
							width: thisWIDTH,
							height: thisHEIGHT,
							alt: thisALT
						});
					}
					*/
					$('a.propose_hide').click(function() {
						var s = $(this).parents('div.search_results.s_opened');
						s.prev().show();
						s.hide();
					});
				});
				
			}
		}
		
	});
	
	var searchResultsEvents = function() {
		//tm.hotelMapping.lnkSystemHotelSearchClick();
		$('.transfers-block-show a').click(function() {
			$(this).parents('.transfers-block-show').siblings('.transfers-block').show();
			$(this).parents('.transfers-block-show').hide();
		});
		$('.transfers-block-hide a').click(function() {
			$(this).parents('.transfers-block').siblings('.transfers-block-show').show();
			$(this).parents('.transfers-block').hide();
		});

		$('.propositions .d_propositions div.service_choose div.row').mouseover(function() {
			var $this = $(this);
			if (!$this.hasClass('selected')) {
				$this.addClass('hovered');
			}
		});
		
		$('div.service_choose div.row').mouseout(function() {
			$(this).removeClass('hovered');
		}).mousedown(function() {
			var $this = $(this);
			
			var vc = $this.parents('.service_choose').find('div.selected input.vendor-code').val();
			var rc = $this.parents('.service_choose').find('div.selected input.room-code').val();
			var vendor = (vc == 'hotelbeds' || vc.match(/hotelspro/)) ? true : false;
			var roomCode = $this.children('input.room-code').val();
			var thisVC = $this.find('input.vendor-code').val();

			if ($this.parents('.service_choose').find('input.vendor-sync').length > 0) {
				if (thisVC != 'hotelbeds' /*&& thisVC.match(/hotelspro/) === null*/ && vendor) {
					var mustBeSelected = $this.parents('div.service_choose').siblings('div.service_choose').filter(function() {
						return $(this).find('input.vendor-sync').length > 0;
					}).find('div.row').filter(function() {
						var c = $(this).find('input.vendor-code').val();
						return (c != 'hotelbeds' && c.match(/hotelspro/) == null);
					});
					
					mustBeSelected.addClass('mustBeSelected');
					mustBeSelected = mustBeSelected.parents('div.service_choose').find('.mustBeSelected:first');
					
					mustBeSelected.parents('div.service_choose').find('div.row').removeClass('selected');
					mustBeSelected.parents('div.service_choose').find('a.tm-radiobutton img').removeClass('checked');
					mustBeSelected.find('input[type="radio"]').trigger('click').next(0).find('img').addClass('checked');
					mustBeSelected.addClass('selected').removeClass('hovered');
				}
			}

			var vendorSyncInp = '<input type="hidden" disabled="disabled" class="vendor-sync" />';
			$this.parents('div.service_choose').siblings('div.service_choose').find('div.row > input.room-code').each(function(i) {
				var
					inpRoomCode = $(this), 
					inpRoomCodeServiceChoose = inpRoomCode.parents('div.service_choose');
					$thisServiceChoose = $this.parents('div.service_choose')
				;
				if (inpRoomCode.val() == roomCode) {
					inpRoomCodeServiceChoose.find('div.selected').removeClass('selected');
					inpRoomCodeServiceChoose.find('a.tm-radiobutton img').removeClass('checked');
					inpRoomCode.parents('div.row').find('input[type="radio"]').trigger('click').next(0).find('img').addClass('checked');
					inpRoomCode.parents('div.row').addClass('selected').removeClass('hovered');
					
					if (inpRoomCodeServiceChoose.find('input.vendor-sync').length <= 0) {
						inpRoomCodeServiceChoose.append(vendorSyncInp);
					}
					if ($thisServiceChoose.find('input.vendor-sync').length <= 0) {
						$thisServiceChoose.append(vendorSyncInp);
					}
				}
			});
			
			$this.parents('.service_choose').find('div.selected').removeClass('selected');
			$this.parents('.service_choose').find('a.tm-radiobutton img').removeClass('checked');
			$this.find('input[type="radio"]').trigger('click').next(0).find('img').addClass('checked');
			$this.addClass('selected').removeClass('hovered');

			recalculatePrice(this);
		});
		
		
		var recalculatePrice = function(elm) {
			var cashType, transferPrice, summary, summaryPrice, roomPrice = [], roomPriceAll = 0, cashAfter = false;
			
			summary = $(elm).parents('form.propositions').find('.search_result_bottom .summary .summ');

			$(elm).parents('form.propositions').find('.room_choose').each(function() {
				var
					$this = $(this),
					prc = $this.find('.row.selected .price').length > 0 ? $.trim($this.find('.row.selected .price strong').text()) : '0'
				;
				roomPrice.push(prc);
			});
			
			if ($(elm).parents('form.propositions').find('.transfer_choose').length > 0) {
				transferPrice = $(elm).parents('form.propositions').find('.transfer_choose .selected .price').html().replace(/(^\s+)|(\s+$)/gi, '');
			} else {
				transferPrice = '';
			}

			/*for (var j = 0; j < roomPrice.length; j++) {
				if (roomPrice[j].length > 1 && roomPrice[j] != null) {
					cashType = roomPrice[j].match(/(^\S)/gi);
					break;
				} else if (transferPrice.length > 1 && transferPrice != null) {
					cashType = transferPrice.match(/(^\S)/gi);
					break;
				} else {
					cashType = '';
					break;
				}
			}*/

			if (roomPrice[0].length > 0 && roomPrice[0] != null) {
				cashType = roomPrice[0].replace(/[0-9]+/gi, '');
				if (isNaN(parseInt(roomPrice[0].substr(0,1))))
					cashAfter = false;
				else
					cashAfter = true;
			} else
				cashType = '';

			for (var i = 0; i < roomPrice.length; i++) {
				roomPrice[i] = (roomPrice[i].length > 1 && roomPrice[i] != null) ? roomPrice[i].match(/[0-9]+/gi, '') : '0';
				roomPriceAll += parseInt(roomPrice[i]);
			}
			transferPrice = (transferPrice.length > 1 && transferPrice != null) ? transferPrice.replace(/(^\S)/gi, '') : '0' ;

			summaryPrice = roomPriceAll + parseInt(transferPrice);
			var resultText = '';
			if (cashAfter) {
				resultText = summaryPrice + '' + cashType;
			} else {
				resultText = cashType + '' + summaryPrice;
			}
			summary.text(resultText);
		};
		
	}
	
	var expandHotelElem = $('a.propose_show').filter(function(i) {
		var v = $(this).metadata().expandHotel;
		return (v != undefined && v.length > 0);
	}).eq(0);
	if(expandHotelElem.size() == 1) {
		expandHotelElem.trigger('click');
	}
	
	if ($('div.search_results').length > 0) {
		var hIndexes = [];
		var hImages = [];
		var hCC = [];
		var hDC = [];
		
		$('.search_results .search_results_item .photo a img.default').each(function() {
			hIndexesIndex = $(this);
			hIndexes.push(hIndexesIndex.parents('a').metadata().index);
			hCC.push(hIndexesIndex.parents('a').metadata().cc);
			hDC.push(hIndexesIndex.parents('a').metadata().dc);
			hImages.push(hIndexesIndex);
		});
		var i = 0;
		var numOfIndexes = hIndexes.length;
		
		if (numOfIndexes > 0) {
			ajaxReq(hIndexes, hCC, hDC, hImages, i, numOfIndexes);
		}
	}
	
	function ajaxReq(codes, hCC, hDC, images, i, numOfIndexes) {
		var vendorId = '';
		if(location.href.match(/vendor=/i)) {
			var vendorStr = location.href.substr(location.href.indexOf('vendor='));
			var ampIndex = vendorStr.indexOf('&');
			vendorId = vendorStr.substr(vendorStr.indexOf('=') + 1);
			if (ampIndex > -1)  {
				vendorId = vendorId.substr(0, vendorId.indexOf('&') );
			}
		}

		if($('#iLoadHotelsContent').val() == 0) {
			return;
		}

		var ajaxData = {hc: codes[i], cc: hCC[i], dc: hDC[i], vendor: vendorId};

		/* Simple correction (if vendorId is undefined - remove it from data array) */
		if (vendorId == '') {
			delete ajaxData['vendor'];
		}

		$.ajax({
			url: '/a_ajax/content/hotel',
			data: ajaxData,
			dataType : "json",
			type: 'GET',
			
			beforeSend: function() {
				images[i].after('<img class="ajax-loader" src="/i/ajax-loader-transparent.gif" width="35" height="35" alt="" />');
			},
			success: function(res){
					// error = 0 - not errors;
					// error = 1 - empty hotel code or country code
					// error = 2 - if content hotel exist or vendor - S2S
					// error = 3 - empty content hotel
					// error = 4 - content not saved
					// error = 5 - exception
					// error = 6 - empty image src
				if (res.error == 0 && res.src != '') {
					images[i].removeClass('default').attr({
						src: res.src,
						width: res.width,
						height: res.height
					});
					images[i].next('img.ajax-loader').remove();
				}
				if (res.error != 0) {
					images[i].removeClass('default');
					images[i].next('img.ajax-loader').remove();
				}
				if (i < numOfIndexes - 1) {
					i++;
					ajaxReq(codes, hCC, hDC, images, i, numOfIndexes);
				} else {
					return;
				}
  			},
			error: function() {
				if (images[i+1] != undefined) {
					i++;
					ajaxReq(codes, hCC, hDC, images, i, numOfIndexes);
				}
				images[i].removeClass('default');
				images[i].next('img.ajax-loader').remove();
			}
		});
	}
	
/*	function searchWaitRedirect(e) {
		if (!location.href.match(/expandHotel/)) {
			var domain = location.href + '&expandHotel=' + e;
			location.href = domain;
		}
	}*/

});